var express = require('express');
var router = express.Router();
var db = require('../config/mysql');
var vertoken = require('../config/token');

//引入 alipay sdk 模块
const AliPaySdk = require('alipay-sdk').default
//引入 alibapay form 模块
const AlipayForm = require('alipay-sdk/lib/form').default

//初始化alipay 配置，以下为支付宝沙箱配置
const alipaySdk = new AliPaySdk({
	appId: '2021000120614771', // 应用的id
	gateway:"https://openapi.alipaydev.com/gateway.do", // 支付宝网关
	// 应用私钥
	privateKey: "MIIEowIBAAKCAQEAhTQeKQLkH/6I4con0pcY0CQcqx0MV7WVD6hCC/OSRd4GFWu5Q7taApx+r3moZlhyP0bO+NfeILSq/GElh5LLT4FVDuQWq9UM/V/FrZk7Zh+LkjBQEkS3HW3DkrSpxwung2YNE/zyX1FvT9YSa5VmXgGJ+ma6YOBPDOKwnqeU+QCopq15Svh87embMzratxZ/Xv/KOFt+/6gPu5QhPP+kg/eFB6EfoNHCHK7H2wlNidckGQb32EYRnDZzLvx5I1Jvu7CuzA6RELoY667/tQTqO2QLJzgXJPmR8/EnAPCWGQF+T+opp8mhnfNMnVd1UdLJ2XqX7BGbG6abBulj0nKAnQIDAQABAoIBAAwBhZJmu08S7x2CzhISIl9oUdkudhVVvYi6vrE7E/0OJPg7TGiJc3R2zIhea8pFwI5pgHA3bML/5cV3sB1HIuIYoyUDc/Oq8U/JGRUrkYoD392eUylCXkrdwNnxRLg3GbMjOJyLmQD0YxcMEX726VIhy2Dxb20Z6qYbrJWwPyIuRnyap60ZIsEufg2FBoPzfgHhr5vG+3t/Ac3oQHPkYd9nudC/cIbE/F++rAWT8l8smfuUbc38Un8cur1ccNIgW/X2Zw0wqZRsQmRmfnbecptFX01XSZX4+5Ro85wGtYckjWXeaTy1AG0yofDI1JwsV5w+vGhPEPRj1pdFXvL2x5UCgYEA0HiTS9hvOMS4fy4eThD4FysAzW9H++9yRdGi7fIB96hH/CT/JxUWZhP1HW5x58DRLtZL2f8xJtqZSY2ARP2LH+7IbnNLChnh18se7v2GUV3HIT956yEjMCUEWtt9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9HYIdg7o5aPP/lhK0APvc+j3eYImtsrsUeeIjtuHXvP1fPvyku8RA1aOeEwC97I9gx01w+CCl4GQIDAQAB"
})

// 生成唯一订单号
function generateOrderNumber(length=4){
 const now = new Date();
 let year=now.getFullYear().toString();
 let month = (now.getMonth() + 1).toString();
 let day = now.getDate().toString();
 let hour = now.getHours().toString();
 let minutes = now.getMinutes().toString();
 let seconds = now.getSeconds().toString();
 // 存放订单号
 let num = '';
 // N位随机数(加在时间戳后面)
 for (var i = 0; i < length; i++)
 {
	 num += Math.floor(Math.random() * 10);
 }
	 return year+month+day+hour+minutes+seconds+num;
}

// 创建alipay实例
const formData = new AlipayForm();

// 调起支付
router.post('/pay', async (req, res) => {
  let { pirce } = req.body;

	formData.setMethod('get')
	formData.addField('notifyUrl', 'http://localhost:8088/tool/pay'); //支付成功的回调
	// formData.addField('notifyUrl', 'http://101.43.202.129:3003/alipay/callback'); //支付成功的回调
	formData.addField('bizContent', {
   		outTradeNo: generateOrderNumber(), // 订单号
   		productCode: 'FAST_INSTANT_TRADE_PAY', // 产品码
    	totalAmount: pirce || '0.01', // 商品金额
    	subject: '测试商品，请勿支付', // 出售商品的标题
    	body: '请勿支付！！！' // 出售商品的内容
	});
	formData.addField('returnUrl', 'http://www.renyuhang.com/tool/pay'); //支付成功的回调
	// formData.addField('returnUrl', 'http://www.renyuhang.com:3003/alipay/callback'); //支付成功的回调

  //执行结果
 	const data = await alipaySdk.exec('alipay.trade.page.pay', {}, { formData: formData })

	res.json({
    status: 200,
    message: '成功',
    data,
    timestamp: db.getTime()
  })
})

// 支付回调
router.post('/callback', (req, res) => {
	console.log(req.headers)
	console.log(vertoken.getToken(req.headers.authorization))
	console.log('--------------------------------------------------------------')
	// console.log(req.query)
	// query: {
  //   charset: 'utf-8',
  //   out_trade_no: '20227251749532172',
  //   method: 'alipay.trade.page.pay.return',
  //   total_amount: '17.80',
  //   sign: 'OL6a/N4jbZ+/ANwAE+swo9Mq33SHYoKVie5nva4h3dgA9l1NIR1/u7lbndgi9Lx2ZbrpVJGMBrIjl+IbzDRGIOaBlNyctnhOgpowMyJUltTFunAqov7agn9MxrbATPXsJP46ke4aqE3nyomCx07ELx2MbnDO6UGzWbPgTC3p1p2G5M+00QDE0J7m6xdIGT5DmrX6lSIMb/cnbvjtnfd4bQ9XgdkGvsmcUTOnxKtuAmq8AwlwtWlQt8CME9U6WabtKnQeE/DLJT+JweHQ2I31wY0vVSURQP+evGDIgtYfVOqvAIph0O+zp49eJGw6B8ugSMQyfAZhGMOJ9J+G1/n11g==',
  //   trade_no: '2022072522001465950501784964',
  //   auth_app_id: '2021000120614771',
  //   version: '1.0',
  //   app_id: '2021000120614771',
  //   sign_type: 'RSA2',
  //   seller_id: '2088621959392880',
  //   timestamp: '2022-07-25 17:50:16'
  // },
  // 支付成功插入订单信息
  // let sql = `INSERT INTO menu (parentId, name, url, iconPath) VALUES (?, ?, ?, ?)`;
  // db.query(sql, [buttonName, buttonKey, menuId], (reslute) => {
  //   res.json({
  //     status: 200,
  //     message: '成功',
  //     data: reslute,
  //     timestamp: db.getTime()
  //   })
  // })
})

// 交易查询
router.get('/query', async (req, res) => {
	// console.log(req)
	formData.setMethod('get')
	formData.addField('bizContent', {
   		outTradeNo: 66888881111, // 订单号
	});

  //执行结果
 	const data = await alipaySdk.exec('alipay.trade.query', {}, { formData: formData })

	res.json({
    status: 200,
    message: '成功',
    data,
    timestamp: db.getTime()
  })
})

// 交易退款
router.post('/refund', async (req, res) => {
	formData.setMethod('get')
	formData.addField('bizContent', {
   		outTradeNo: 66888881111, // 订单号
	});

  //执行结果
 	const data = await alipaySdk.exec('alipay.trade.query', {}, { formData: formData })

	res.json({
    status: 200,
    message: '成功',
    data,
    timestamp: db.getTime()
  })
})

module.exports = router;